package com.yzj.android.servlet;

import com.google.gson.Gson;
import com.yzj.Bean.Cake;
import com.yzj.Bean.Cart;
import com.yzj.android.service.CakeService;
import com.yzj.android.service.CartService;
import com.yzj.android.service.impl.CakeServiceImpl;
import com.yzj.android.service.impl.CartServiceImpl;
import com.yzj.android.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

public class CartServlet extends BaseServlet {
    CakeService cakeService = new CakeServiceImpl();
    CartService cartService = new CartServiceImpl();
    Gson gson = new Gson();
    protected void addItems(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int id = WebUtils.StringToInt(req.getParameter("id"),0);
        String username = req.getParameter("username");
        Cake cake = cakeService.queryCakeById(id);
        //获取到了需要添加到购物车的信息
        Cart cart = new Cart(username,new Integer(cake.getId()),cake.getName(),1,null,new BigDecimal(cake.getPrice()),null,null,cake.getPic());
        cartService.addItems(cart);
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write("已经将蛋糕添加到购物车");
    }
    protected void showItems(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        //根据用户名查询购物车商品 并以json 数据形式发给客户端
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write( gson.toJson(cartService.queryItems(username)));


    }
}
